package com.lyf.language.practice.practice_6_21.io.network.tcpv2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author LYF
 * @date 2022/6/22
 */
public class Client1 {
    /**
     * ThreadPool
     */
    final static ThreadPoolExecutor executor =
            new ThreadPoolExecutor(2,5,2,
                    TimeUnit.SECONDS,new LinkedBlockingQueue<>());

    /**
     * Server
     */
    static void client(){
        Socket client =null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.println("waiting connect...");
            client = new Socket("127.0.0.1",8888);
            System.out.println("connect successfully...");
            // 监听消息
            while (true){

                outputStream = client.getOutputStream();
                System.out.println("reply:");
                outputStream.write(scanner.nextLine().getBytes(StandardCharsets.UTF_8));



                inputStream = client.getInputStream();
                byte[]bytes = new byte[1024];
                int readN = inputStream.read(bytes);//暂定可一次读取完毕
                System.out.println("receive from server-"+client.getRemoteSocketAddress()+"::"+new String(bytes,0,readN));

            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(client!=null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) {
        client();
    }


}
